package cn.kgc.vue.shiro;

import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.LinkedHashMap;

/**
 * @author 课工场
 * @date 2023/12/2
 * @description
 */
@Configuration
public class ShiroWebConfig {

    //  shiro 过滤器
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);


        LinkedHashMap<String, Filter> filters = new LinkedHashMap<>();
        filters.put("kgc",new JWTFilter());
        //  添加自定义filter到shiro中
        shiroFilterFactoryBean.setFilters(filters);
        //  资源权限
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        map.put("/captcha", "anon");
        map.put("/users/login", "anon");
        //  放行swagger相关请求
        map.put("/doc.html", "anon");
        map.put("/swagger-resources", "anon");
        map.put("/v2/api-docs", "anon");
        map.put("/webjars/css/app.b2512131.css", "anon");
        map.put("/webjars/js/chunk-vendors.9ff0f717.js", "anon");
        map.put("/webjars/js/app.ed549958.js", "anon");

        map.put("/**","kgc");  //  authc  session

        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        shiroFilterFactoryBean.setLoginUrl("/users/authenticate");
        return shiroFilterFactoryBean;
    }

    //  安全管理器
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(Realm realm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(realm);
        return defaultWebSecurityManager;
    }

    // realm
    @Bean
    public Realm realm() {
        CustomerRealm customerRealm = new CustomerRealm();
        //  创建MD5的凭证匹配器
        // HashedCredentialsMatcher md5 = new HashedCredentialsMatcher("MD5");
        //         // md5.setHashIterations(1024);
        //         // customerRealm.setCredentialsMatcher(md5);
        return customerRealm;
    }
}
